package com.diankangwo.controller;

import com.diankangwo.constant.resultMsg;
import com.diankangwo.dao.UserDAO;
import com.diankangwo.domain.UserInfo;
import com.diankangwo.upyun.demo.PicBucketDemo;
import com.diankangwo.util.FileUpLoadUtil;
import com.diankangwo.util.LoadPropertyUtil;
import com.diankangwo.util.QRCoderUtil;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Properties;

@Controller
@RequestMapping("/qrcode")
public class QRCodeController {

    @Autowired
    private UserDAO userDAO;

    Properties prop = LoadPropertyUtil.loadProperty("qrcode.properties");

    /**
     * 生成/获取分享二维码
     *
     * @param request
     * @param content
     * @param accessToken
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get")
    public String getQRCode(HttpServletRequest request, String content, String accessToken) {
        UserInfo user = userDAO.getUserByToken(accessToken);
        String path = System.getProperty("user.dir");
        QRCoderUtil util = new QRCoderUtil();
        String code = "2";
        String msg = "处理异常！";
        if (user == null) {
            msg = "token无效！";
            return resultMsg.mapToJson(code, msg, "");
        }
        if (user.isPort()) {
            try {
                String fileName = System.currentTimeMillis() + "";
                String url = util.encoderQRCoderFile(content, path);
                File file = new File(url);
                String codePath = PicBucketDemo.WriteFile("/qrcode/", file, fileName);
                user.setQrcode(codePath);
                userDAO.saveOrUpdate(user);
                FileUpLoadUtil fileUpLoadUtil = new FileUpLoadUtil();
                boolean deleteImage = fileUpLoadUtil.removeFile(request, url, "");
            } catch (WriterException e) {
                e.printStackTrace();
            }
            code = "1";
            msg = "生成成功！";
            return resultMsg.mapToJson(code, msg, user.getQrcode());
        } else {
            code = "2";
            msg = "该用户不是端口用户，无法分享！";
            return resultMsg.mapToJson(code, msg, "");
        }

    }

}
